package com.example.myapplication.status2;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 文件相关工具
 */

public class FileUtils {
    private static final ExecutorService mSingleExecutor = Executors.newSingleThreadExecutor();
    private static final ExecutorService mCachedExecutor = Executors.newCachedThreadPool();

    public static ExecutorService getSingleExcutor() {
        return mSingleExecutor;
    }

    public static ExecutorService getCachedExcutor() {
        return mCachedExecutor;
    }

    /**`
     * 文件转化为base64编码文件
     */
    public static String image2Base64(String path) {
        InputStream is = null;
        byte[] data;
        String result = null;
        try {
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            //用默认的编码格式进行编码
            result = Base64.encodeToString(data, Base64.DEFAULT);
        } catch (IOException e) {

        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {

                }
            }
        }
        return result;
    }

    /**
     * base64编码文件转化为bitmap
     */
    public static Bitmap base642Bitmap(String base64Str) {
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray = Base64.decode(base64Str.split(",")[1], Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }


    /**
     * base64编码文件转化为文件
     */
    private static void base642Image(String base64Str, String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }
        byte[] data = Base64.decode(base64Str, Base64.DEFAULT);
        for (int i = 0; i < data.length; i++) {
            if (data[i] < 0) {
                //调整异常数据
                data[i] += 256;
            }
        }
        OutputStream os = null;
        try {
            os = new FileOutputStream(path);
            os.write(data);
            os.flush();
        } catch (Exception e) {

        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {

                }
            }
        }
    }

    /**
     * 清空文件夹
     */
    public static void deleteFile(String path) {
        File file = new File(path);
        if (file.isDirectory() && null != file.listFiles()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                deleteFile(f.getPath());
            }
        } else if (file.exists()) {
            file.delete();
        }
    }



    /**
     * 质量压缩方法
     *
     * @param path
     * @return
     */
    public static boolean compressImage(String path) {
        Bitmap image = BitmapFactory.decodeFile(path);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 100;
        // 循环判断如果压缩后图片是否大于500kb,大于继续压缩
        while (baos.toByteArray().length / 1024 > 500) {
            baos.reset();
            //第一个参数 ：图片格式 ，第二个参数： 图片质量，100为最高，0为最差  ，第三个参数：保存压缩后的数据的流
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
        }
        File file = new File(path);
        boolean operateFlg = true;
        if (file.exists()) {
            operateFlg = file.delete();
        }
        if (operateFlg) {
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(file);
                baos.writeTo(fos);
            } catch (Exception e) {
                return false;
            } finally {
                try {
                    if (fos != null) {
                        fos.close();
                    }
                    if (baos != null) {
                        baos.close();
                    }
                } catch (IOException e) {

                }
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * 尺寸压缩方法
     *
     * @param path
     * @param rqsW
     * @param rqsH
     * @return
     */
    public static boolean compressImage(String path, int rqsW, int rqsH) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;// 设置仅读取Bitmap的宽高而不读取内容
        BitmapFactory.decodeFile(path, options);// 获取到图片的宽高，放在option里边
        final int height = options.outHeight;// 图片的高度放在option里的outHeight属性中
        final int width = options.outWidth;
        int inSampleSize;
        if (rqsW == 0 || rqsH == 0) {
            options.inSampleSize = 1;
        } else if (height > rqsH || width > rqsW) {
            final int heightRatio = BigDecimal.valueOf(height).divide(BigDecimal.valueOf(rqsH), 2, RoundingMode.HALF_UP).intValue();
            final int widthRatio = BigDecimal.valueOf(width).divide(BigDecimal.valueOf(rqsW), 2, RoundingMode.HALF_UP).intValue();
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
            options.inSampleSize = inSampleSize;
        }
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(path, options);
        File file = new File(path);
        boolean operateFlg = true;
        if (file.exists()) {
            operateFlg = file.delete();
        }
        if (operateFlg) {
            BufferedOutputStream bos = null;
            try {
                bos = new BufferedOutputStream(new FileOutputStream(file));
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                bos.flush();
            } catch (IOException e) {
                return false;
            } finally {
                try {
                    if (bos != null) {
                        bos.close();
                    }
                } catch (IOException e) {

                }
            }
            return true;
        } else {
            return false;
        }
    }

}